package net.xdclass.xdclass.service.impl;

import net.xdclass.xdclass.mapper.UserMapper;

import net.xdclass.xdclass.model.pojo.User;
import net.xdclass.xdclass.service.UserService;
import net.xdclass.xdclass.utils.CommonUtils;
import net.xdclass.xdclass.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import java.util.Random;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;
    @Override
    public int save(Map<String, String> userInfo) {
         User user= parseToUser(userInfo);
         if (user!=null){
             return userMapper.save(user);
         }else {
             return -1;
         }


    }

    @Override
    public String findByPhoneAndPwd(String phone, String pwd) {

        User user = userMapper.findByPhoneAndPwd(phone,CommonUtils.MD5(pwd));
        if (user==null){
            return null;
        }else {
            return JWTUtils.geneJsonWebToken(user);
        }
    }

    @Override
    public User findByUserId(Integer userId) {
        return userMapper.findByUserId(userId);

    }


    private User parseToUser(Map<String, String> userInfo) {

        if (userInfo.containsKey("phone") && userInfo.containsKey("pwd") &&
           userInfo.containsKey("name")){
            User user = new User();
            user.setName(userInfo.get("name"));
            user.setCreateTime(new Date());
            user.setPhone(userInfo.get("phone"));
            String pwd = userInfo.get("pwd");
            user.setPwd(CommonUtils.MD5(pwd));
            user.setHeadImg(getRandomImg());
            return user;
        }else {
            return null;
        }

    }
    /**
     * 放在CDN上的随机头像
     */
    private static final String [] headImg = {
            "https://xd-video-pc-img.oss-cn-beijing.aliyuncs.com/xdclass_pro/default/head_img/12.jpeg",
            "https://xd-video-pc-img.oss-cn-beijing.aliyuncs.com/xdclass_pro/default/head_img/11.jpeg",
            "https://xd-video-pc-img.oss-cn-beijing.aliyuncs.com/xdclass_pro/default/head_img/13.jpeg",
            "https://xd-video-pc-img.oss-cn-beijing.aliyuncs.com/xdclass_pro/default/head_img/14.jpeg",
            "https://xd-video-pc-img.oss-cn-beijing.aliyuncs.com/xdclass_pro/default/head_img/15.jpeg"
    };

    private String getRandomImg(){
        Random random = new Random();
        int i = random.nextInt(headImg.length);
        return headImg[i];
    }


}
